package require http

proc get_css {ad i_deb i_fin {step 1}} {
 for {set i $i_deb} {$i <= $i_fin} {incr i} {
   set index [format %03i $i]
   puts "::http::geturl $ad/${index}/${index}.css"
   set token [::http::geturl "$ad/${index}/${index}.css" -command "write_page $ad $index ${index}.css"]
   if {$i % $step == 0} {
     puts "Waiting for $token (#$i)"
	 ::http::wait $token
    }
  }
}

proc write_page {ad index name token} {
 set directory $index
 file mkdir $directory

 set txt [::http::data $token]

 set f [open $directory/$name w]
	 # Analyse to download also images
	 foreach l [split $txt "\n"] {
	   if {[regexp {url\((.*)\)} $l reco Limg]} {
		 puts -nonewline "Image detected for download : $Limg"
		 set img [lindex [split $Limg "/"] end]
		 puts "  => $ad/$index/$img"
		 ::http::wait [::http::geturl "$ad/$index/$img" -binary 1 -command "write_image $ad $index $img"]
		 puts $f [string map [list $Limg $img] $l]
		} else {puts $f $l}
	  }

 close $f
 puts "Done $name !"
}


proc write_image {ad index img_name token} {
 set f [open $index/$img_name w]
   fconfigure $f -encoding binary -translation binary
   puts -nonewline $f [::http::data $token]
 close $f
 
 puts "  Image $img_name done !"
}
